#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
@Author: 李吉凯
@Email: lijk34925@hundsun.com
@Time: 2022/6/16 9:46
@File: 风险评估指标_权重调整.py
"""

import re

from qturboframe.lib.utils.by import By
from qturboframe.lib.webdriver import SeleniumError
from BladeFerm.Lib.Common import logger, data_processing, DownPath
from BladeFerm.hui2_app import FE

from 基础公共脚本.公共方法_hui2 import open_menu
from 基础公共脚本.步骤检查_hui2 import check_ele_text


@data_processing
def product_risk_review_adjust(input_data=None, ui_expect=None):
    open_menu({'子系统名称': '反洗钱系统', '菜单名称': '产品风险评估/产品风险评估规则'})
    # 点击 修改
    button_click("修改")
    # 修改 权重
    for key, value in input_data.items():
        logger.info(f'调整数据： {key}, {value}')
        modify_weight(key, value)
    # 点击 提交
    button_click("提交")
    # 检查结果
    check_result()
    # 点击确认
    msg = FE.msg_box(text='确认')
    # 弹框确认
    msg.click(ui_expect.get("是否继续"))
    # 断言
    check_ele_text(ui_expect=ui_expect)


@data_processing
def product_risk_rule_add(input_data=None, ui_expect=None):
    open_menu({'子系统名称': '反洗钱系统', '菜单名称': '产品风险评估/产品风险评估规则'})

    # 点击 修改
    button_click(name="新增", index=2)

    # 填值
    form = FE.form("新增类别")
    form.auto_fill_group(input_data)

    # 点击提交
    express = f'//div[@class="h-modal-footer"]//button/span[contains(text(),"提交")]//parent::button'
    FE.button(idname={By.XPATH: express}).click()

    # 断言 产品风险评估配置
    check_ele_text(ui_expect=ui_expect)


def button_click(name="修改", index=1):
    FE.button(idname={'xpath': f'//div[contains(@class,"button-wrap")]/button/span[contains(text(),"{name}")]'
                               f'//parent::button'}, index=index).click()
    logger.info(f"点击 <{name}> 按钮")


def check_result():
    tar = FE.driver.exist('xpath', './/div[contains(@class,"sum-score")]/span[contains(text(), "权重汇总")]')
    cur_text = tar.text
    cur_weight_score = int(re.search(r'\d+', cur_text).group())
    if cur_weight_score == 100:
        logger.info(f'调整后的结果是100，ok')
        return True
    else:
        logger.warning(f'调整后的结果是{cur_weight_score}，请检查输入数据')
        return False


def modify_weight(key, value):
    '''
    单个指标 数据调整
    :param adjust_data:
    :return:
    '''
    target_path = key
    delete_status = value.get('是否删除', None)
    weight_value = value.get('指标权重', None)
    target_row = target_path.split('/')
    target_name = target_row[-1]

    # 找表格对象
    base_table = FE.table_base(idname={'xpath': './/div[@class="amlra-tables"]/table'})
    merge_table_first(base_table._element)
    # 展开第1层表格
    first_table = expand_table(text=target_row[0], father=base_table._element)
    # 展开第2层表格
    target_table = expand_table(text=target_row[1], father=first_table)
    if len(target_row) == 3:
        # 展开第3层表格
        target_table = expand_table(text=target_row[2], father=target_table)
    # 找到指标的目标行
    target_table_row = found_target_row(target_name, target_table)
    if weight_value:
        adjust_weight(target_name, weight_value, target_table_row)
        logger.info(f'调整 {target_name} 的值为 {weight_value}')
    if delete_status == '是':
        FE.button(idname={'xpath': './/td/a[@class="edit-btn" and contains(text(), "删除")]'}, father=target_table_row).click()
        logger.info(f'删除 {target_name}')


def merge_table_first(father):
    '''
    合起所有一级表格
    Args:
        father:

    Returns:

    '''
    unexpand_status = r'h-icon-android-arrow-dropdo'
    xpath_express = f'./tbody/tr/th[1]/i'
    base_table_tds = father.find_elements_by_attribute('xpath', xpath_express)
    for unit in base_table_tds:
        cur_class = unit.get_attribute('class').split(' ')
        if unexpand_status in cur_class:
            unit.click()
            second = unit.find_element_by_attribute('xpath', './/following-sibling::span')
            logger.info(f'合起 {second.text}')


def expand_table(text, father):
    '''
    根据 text 查找所在的td单元格，查看是否展开？
    之后返回 td 所在的列表。
    :param text:
    :param father:
    :return:
    '''
    unexpand_status = r'h-icon-android-arrow-dropri'
    xpath_express = f'.//tr//*[contains(text(),"{text}")]'
    base_table_td = father.find_element_by_attribute('xpath', xpath_express)
    base_table_icon = base_table_td.exist('xpath', './/preceding-sibling::i[contains(@class,"h-icon")]')
    if base_table_icon:
        base_table_icon_class = base_table_icon.get_attribute('class').split(' ')
        if unexpand_status in base_table_icon_class:
            base_table_icon.click()
            logger.info(f'展开 {text}')
        else:
            logger.info(f'{text} 已经展开。')
    else:
        logger.warning(f'{text} 没有前缀图标')
    cur_table_ele = base_table_td.find_element_by_attribute('xpath', './/ancestor::table[1]')
    return cur_table_ele


def found_target_row(text, father):
    '''
    查找 指标名称 所在的目标行
    :param text:
    :param father:
    :return:
    '''
    xpath_express = f'.//tr/td/span[contains(text(),"{text}")]'
    base_table_td = father.find_element_by_attribute('xpath', xpath_express)
    return base_table_td.find_element_by_attribute('xpath', './/ancestor::tr[1]')


def adjust_weight(name, score, father):
    '''
    设置 指标得分
    :param name: 指标名称
    :param score: 指标得分
    :param father:
    :return:
    '''
    input_xpath = './/following-sibling::td//input[@class="h-input-number-input"]'
    input_ele = father.exist('xpath', input_xpath)
    if input_ele:
        input_ele.clear()
        input_ele.send_keys(str(score))
        logger.info(f'设置指标 {name} 得分为 {score}')
    else:
        raise SeleniumError(f'指标 {name} 不存在权重调整输入框，请检查！')